from django.db.models import F
from apps.system.user.dao import UserDao
from apps.system.activityPerformance.dao import ActivityPerformanceDao

# 更新直推成员营业额
def updateSelfPerformance(scene, user, n, money, activity=None):
    # print('更新', scene, user.id, n)
    if user and user.id:
        # 更新团队总人数
        _user = UserDao().findOneByObjId(user.id)
        if activity:
            _activityPerformance = None
            _activityPerformances = ActivityPerformanceDao().findAll().filter(activity=activity, user=_user)
            if _activityPerformances.exists():
                _activityPerformance = _activityPerformances.first()
            else:
                _activityPerformance = ActivityPerformanceDao().create({'activity': activity.id, 'user': _user.id})

            if scene == 'add':
                _activityPerformance.verticalOrderNumber = F('verticalOrderNumber') + n
                _activityPerformance.verticalPerformance = F('verticalPerformance') + money
                _activityPerformance.save()
            elif scene == 'sub':
                if _activityPerformance.verticalOrderNumber >= n:
                    _activityPerformance.verticalOrderNumber = F('verticalOrderNumber') - n
                    _activityPerformance.save()
                else:
                    _activityPerformance.verticalOrderNumber = 0
                    _activityPerformance.save()

                if _activityPerformance.verticalPerformance >= money:
                    _activityPerformance.verticalPerformance = F('verticalPerformance') - money
                    _activityPerformance.save()
                else:
                    _activityPerformance.verticalPerformance = 0
                    _activityPerformance.save()
        else:
            if scene == 'add':
                _user.verticalOrderNumber = F('verticalOrderNumber') + n
                _user.selfPerformance = F('selfPerformance') + money
                _user.save()
            elif scene == 'sub':
                if _user.verticalOrderNumber >= n:
                    _user.verticalOrderNumber = F('verticalOrderNumber') - n
                    _user.save()
                else:
                    _user.verticalOrderNumber = 0
                    _user.save()

                if _user.selfPerformance >= money:
                    _user.selfPerformance = F('selfPerformance') - money
                    _user.save()
                else:
                    _user.selfPerformance = 0
                    _user.save()
    else:
        return False

